/**
 * Created by 顾杰 on 2017/5/9.
 */
import React from 'react';
import { connect } from 'dva';
import { ListView } from 'antd-mobile';
import styles from './index.less';

const empty = require('is-empty');
class ListViewItem extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      //分页, 默认true
      pagination: true,
      //每页显示数量
      pageSize: 10,
      //ListView数据
      data: [],
      dataSource: {},
      isLast: false
    };
  }

  componentWillMount = () => {
    this.setState({
      data: [],
      dataSource: {},
      isLast: false
    });
    //得到数据源参数
    let payload = {};
    if(!empty(this.props.pagination) && this.props.pagination == false) {
      payload = {
        in: this.props.in,
        pagination: false,
        code: this.props.dataSourceCode,
        para: this.props.dataSourceParam
      }
    }else {
      payload = {
        in: this.props.in,
        pagination: true,
        code: this.props.dataSourceCode,
        para: this.props.dataSourceParam,
        currentPage: 1,
        pageSize: empty(this.props.pageSize) ? this.state.pageSize : this.props.pageSize
      }
    }
    this.props.dispatch({
      type: 'witListView/init',
      payload: payload
    });
  };

  componentWillReceiveProps = nextProps => {
    if(this.state.dataSource != nextProps.witListView.dataSource) {
      this.setState({
        data: nextProps.witListView.data,
        dataSource: nextProps.witListView.dataSource,
        isLast: nextProps.witListView.isLast
      })
    }
  };

  //下拉加载
  onEndReached = () => {
    if(!this.state.isLast) {
      this.props.dispatch({type: 'witListView/load'});
    }
  };

  render() {
    const {data, dataSource, isLast} = this.state;
    if(empty(dataSource)) {
      return false;
    }
    return (
      <div className="list-view">
        <ListView
         ref="lv"
         dataSource={dataSource}
         renderHeader={this.props.cardCode?() => this.props.headerContent(this.props.cardCode):null}
         renderFooter={() => <div className={styles.listViewFooter}>{!isLast ? '加载中...' : '加载完成'}</div>}
         renderRow={this.props.renderRow}
         className="am-list"
         pageSize={10}
         scrollRenderAheadDistance={500}
         scrollEventThrottle={20}
         onScroll={() => {}}
         useBodyScroll
         onEndReached={this.onEndReached}
         onEndReachedThreshold={100}
         />
      </div>
    );
  }
}

function mapStateToProps({witListView}){
  return {witListView};
}
export default connect(mapStateToProps)(ListViewItem);
